<template>
  <div class="defect-associations-tab">
    <el-tabs v-model="activeSubTab" type="border-card" class="association-sub-tabs">
      <!-- 关联任务子页签 -->
      <el-tab-pane label="关联任务" name="tasks">
        <div class="sub-tab-content">
          <div class="tab-header">
            <div class="header-info">
              <span class="item-count">关联任务（{{ relatedTasks.length }}）</span>
            </div>
            <div class="header-actions">
              <el-button
                type="primary"
                size="small"
                @click="handleAddTask"
              >
                <el-icon><Plus /></el-icon>
                添加任务
              </el-button>
            </div>
          </div>

          <div v-loading="tasksLoading" class="items-list">
            <el-table
              v-if="relatedTasks.length > 0"
              :data="relatedTasks"
              size="default"
              border
              stripe
              style="width: 100%"
            >
              <el-table-column prop="title" label="任务标题" min-width="200" show-overflow-tooltip>
                <template #default="{ row }">
                  <el-link
                    type="primary"
                    @click="handleViewTask(row.id)"
                    :underline="false"
                  >
                    {{ row.title }}
                  </el-link>
                </template>
              </el-table-column>
              <el-table-column prop="status" label="状态" width="100">
                <template #default="{ row }">
                  <el-tag
                    :type="getTaskStatusType(row.status)"
                    size="small"
                  >
                    {{ getTaskStatusName(row.status) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="priority" label="优先级" width="90">
                <template #default="{ row }">
                  <el-tag
                    :type="getTaskPriorityType(row.priority)"
                    size="small"
                  >
                    {{ getTaskPriorityName(row.priority) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="assignee_name" label="负责人" width="100" show-overflow-tooltip />
              <el-table-column prop="due_date" label="截止日期" width="110">
                <template #default="{ row }">
                  {{ formatDate(row.due_date) || '—' }}
                </template>
              </el-table-column>
              <el-table-column label="操作" width="180" fixed="right">
                <template #default="{ row }">
                  <el-button
                    link
                    type="primary"
                    size="small"
                    @click="handleViewTask(row.id)"
                  >
                    查看
                  </el-button>
                  <el-button
                    link
                    type="danger"
                    size="small"
                    @click="handleRemoveTask(row)"
                  >
                    移除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-empty v-else description="暂无关联任务" :image-size="80" />
          </div>
        </div>
      </el-tab-pane>

      <!-- 关联需求子页签 -->
      <el-tab-pane label="关联需求" name="requirements">
        <div class="sub-tab-content">
          <div class="tab-header">
            <div class="header-info">
              <span class="item-count">关联需求（{{ relatedRequirements.length }}）</span>
            </div>
            <div class="header-actions">
              <el-button
                type="primary"
                size="small"
                @click="handleAddRequirement"
              >
                <el-icon><Plus /></el-icon>
                添加需求
              </el-button>
            </div>
          </div>

          <div v-loading="requirementsLoading" class="items-list">
            <el-table
              v-if="relatedRequirements.length > 0"
              :data="relatedRequirements"
              size="default"
              border
              stripe
              style="width: 100%"
            >
              <el-table-column prop="title" label="需求标题" min-width="200" show-overflow-tooltip>
                <template #default="{ row }">
                  <el-link
                    type="primary"
                    @click="handleViewRequirement(row.id)"
                    :underline="false"
                  >
                    {{ row.title }}
                  </el-link>
                </template>
              </el-table-column>
              <el-table-column prop="status" label="状态" width="100">
                <template #default="{ row }">
                  <el-tag
                    :type="getRequirementStatusType(row.status)"
                    size="small"
                  >
                    {{ getRequirementStatusName(row.status) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="priority" label="优先级" width="90">
                <template #default="{ row }">
                  <el-tag
                    :type="getRequirementPriorityType(row.priority)"
                    size="small"
                  >
                    {{ getRequirementPriorityName(row.priority) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="assignee_name" label="负责人" width="100" show-overflow-tooltip />
              <el-table-column prop="created_at" label="创建时间" width="160">
                <template #default="{ row }">
                  {{ formatDate(row.created_at) || '—' }}
                </template>
              </el-table-column>
              <el-table-column label="操作" width="180" fixed="right">
                <template #default="{ row }">
                  <el-button
                    link
                    type="primary"
                    size="small"
                    @click="handleViewRequirement(row.id)"
                  >
                    查看
                  </el-button>
                  <el-button
                    link
                    type="danger"
                    size="small"
                    @click="handleRemoveRequirement(row)"
                  >
                    移除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-empty v-else description="暂无关联需求" :image-size="80" />
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { taskAPI } from '@/api/task'
import type { Task } from '@/api/task'
import type { RequirementResponse } from '@/api/requirements'
import { getRequirementById } from '@/api/requirements'
import { formatDate } from '@/utils/date'
import { useTaskStates } from '@/composables/useTaskStates'
import { useRequirementStates } from '@/composables/useRequirementStates'
import { useRequirementOptions } from '@/composables/useRequirementOptions'
import { versionAPI } from '@/api/version'
import { priorityApi } from '@/api/priority'
import { TASK_PRIORITIES } from '@/types/task'

interface Props {
  defectId: string
  versionIds?: string[]
  projectId?: string
}

const props = defineProps<Props>()

const emit = defineEmits<{
  (e: 'task-updated'): void
  (e: 'requirement-updated'): void
}>()

const router = useRouter()
const activeSubTab = ref('tasks')
const tasksLoading = ref(false)
const requirementsLoading = ref(false)
const relatedTasks = ref<Task[]>([])
const relatedRequirements = ref<RequirementResponse[]>([])

const { loadStates: loadTaskStates, getStateName: getTaskStateName } = useTaskStates()
const { getStateName: getRequirementStateName, getStateColor: getRequirementStateColor, loadStates: loadRequirementStates } = useRequirementStates()
const { getPriorityName: getRequirementPriorityNameFromOptions, getPriorityType: getRequirementPriorityTypeFromOptions, loadOptions: loadRequirementOptions } = useRequirementOptions()

// 任务优先级选项
const taskPriorityOptions = ref<Array<{ value: string; label: string }>>([])

// 加载任务优先级选项
const loadTaskPriorityOptions = async () => {
  try {
    const response = await priorityApi.getAll('task')
    if (response && response.data && response.data.success && response.data.data) {
      taskPriorityOptions.value = response.data.data.map((p: any) => ({
        value: p.code,
        label: p.name
      }))
    } else {
      // 如果API失败，使用默认值
      taskPriorityOptions.value = TASK_PRIORITIES.map(p => ({
        value: p.value,
        label: p.label
      }))
    }
  } catch (error) {
    console.error('加载任务优先级失败:', error)
    taskPriorityOptions.value = TASK_PRIORITIES.map(p => ({
      value: p.value,
      label: p.label
    }))
  }
}

const getTaskStatusName = (status?: string) => {
  if (!status) return '未知'
  return getTaskStateName(status)
}

const getTaskStatusType = (status?: string) => {
  if (!status) return 'info'
  const code = status.toLowerCase()
  if (code === 'done' || code === 'completed') return 'success'
  if (code === 'in_progress' || code === 'inprogress') return 'warning'
  return 'info'
}

const getTaskPriorityName = (priority?: string) => {
  if (!priority) return '未知'
  const option = taskPriorityOptions.value.find(p => p.value === priority)
  return option ? option.label : priority
}

const getTaskPriorityType = (priority?: string) => {
  if (!priority) return 'info'
  const code = priority.toLowerCase()
  if (code === 'urgent' || code === 'critical' || code === 'blocker') return 'danger'
  if (code === 'high') return 'warning'
  if (code === 'medium') return 'success'
  return 'info'
}

const getRequirementStatusName = (status?: string) => {
  if (!status) return '未知'
  return getRequirementStateName(status)
}

const getRequirementStatusType = (status?: string) => {
  if (!status) return 'info'
  const color = getRequirementStateColor(status)
  if (color.includes('green') || color.includes('success')) return 'success'
  if (color.includes('red') || color.includes('danger')) return 'danger'
  if (color.includes('orange') || color.includes('warning')) return 'warning'
  return 'info'
}

const getRequirementPriorityName = (priority?: string) => {
  if (!priority) return '未知'
  return getRequirementPriorityNameFromOptions(priority)
}

const getRequirementPriorityType = (priority?: string) => {
  if (!priority) return 'info'
  return getRequirementPriorityTypeFromOptions(priority)
}

// 加载关联任务
const loadRelatedTasks = async () => {
  if (!props.defectId || !props.versionIds || props.versionIds.length === 0) {
    relatedTasks.value = []
    return
  }

  try {
    tasksLoading.value = true
    await loadTaskStates()
    
    // 通过版本缺陷关联表查询关联的任务
    const allTasks: Task[] = []
    
    for (const versionId of props.versionIds) {
      try {
        const response: any = await versionAPI.getVersionDefects(versionId, { skip: 0, limit: 100 })
        let defects: any[] = []
        
        if (response && response.data) {
          const data = response.data
          if (Array.isArray(data)) {
            defects = data
          } else if (data.success && data.data) {
            if (Array.isArray(data.data)) {
              defects = data.data
            } else if (data.data.items && Array.isArray(data.data.items)) {
              defects = data.data.items
            }
          } else if (data.items && Array.isArray(data.items)) {
            defects = data.items
          }
        }
        
        // 过滤出关联了当前缺陷的任务
        const defectRelations = defects.filter((d: any) => d.defect_id === props.defectId && d.task_id)
        
        // 获取任务详情
        for (const relation of defectRelations) {
          if (relation.task_id) {
            try {
              // 通过版本任务关联表获取任务详情
              const taskRelations = await versionAPI.getVersionTasks(versionId, { limit: 100 })
              const taskRelation = taskRelations.find((tr: any) => tr.task_id === relation.task_id)
              if (taskRelation) {
                // 尝试获取完整任务详情
                try {
                  const taskResponse = await taskAPI.getTask(relation.task_id)
                  if (taskResponse && taskResponse.data) {
                    const task = taskResponse.data
                    if (!allTasks.find(t => t.id === task.id)) {
                      allTasks.push(task)
                    }
                  }
                } catch (error) {
                  // 如果获取详情失败，使用关联表中的基本信息
                  if (taskRelation.task_title) {
                    const task: any = {
                      id: relation.task_id,
                      title: taskRelation.task_title,
                      status: (taskRelation as any).task_status || 'todo',
                      priority: (taskRelation as any).task_priority || 'medium',
                      assignee_name: (taskRelation as any).task_assignee_name,
                      project_id: '',
                      created_at: '',
                      updated_at: ''
                    }
                    if (!allTasks.find(t => t.id === task.id)) {
                      allTasks.push(task)
                    }
                  }
                }
              }
            } catch (error) {
              console.error(`获取任务 ${relation.task_id} 详情失败:`, error)
            }
          }
        }
      } catch (error) {
        console.error(`获取版本 ${versionId} 的缺陷关联失败:`, error)
      }
    }
    
    relatedTasks.value = allTasks
  } catch (error) {
    console.error('加载关联任务失败:', error)
    ElMessage.error('加载关联任务失败')
    relatedTasks.value = []
  } finally {
    tasksLoading.value = false
  }
}

// 加载关联需求
const loadRelatedRequirements = async () => {
  if (!props.defectId || !props.versionIds || props.versionIds.length === 0) {
    relatedRequirements.value = []
    return
  }

  try {
    requirementsLoading.value = true
    await loadRequirementStates()
    await loadRequirementOptions()
    
    // 通过版本缺陷关联表查询关联的需求
    const allRequirements: RequirementResponse[] = []
    const requirementIds = new Set<string>()
    
    for (const versionId of props.versionIds) {
      try {
        const response: any = await versionAPI.getVersionDefects(versionId, { skip: 0, limit: 100 })
        let defects: any[] = []
        
        if (response && response.data) {
          const data = response.data
          if (Array.isArray(data)) {
            defects = data
          } else if (data.success && data.data) {
            if (Array.isArray(data.data)) {
              defects = data.data
            } else if (data.data.items && Array.isArray(data.data.items)) {
              defects = data.data.items
            }
          } else if (data.items && Array.isArray(data.items)) {
            defects = data.items
          }
        }
        
        // 过滤出关联了当前缺陷的需求
        const defectRelations = defects.filter((d: any) => d.defect_id === props.defectId && d.requirement_id)
        
        // 收集需求ID
        for (const relation of defectRelations) {
          if (relation.requirement_id && !requirementIds.has(relation.requirement_id)) {
            requirementIds.add(relation.requirement_id)
            
            // 如果有需求标题，直接使用
            if (relation.requirement_title) {
              allRequirements.push({
                id: relation.requirement_id,
                title: relation.requirement_title,
              } as RequirementResponse)
            }
          }
        }
      } catch (error) {
        console.error(`获取版本 ${versionId} 的缺陷关联失败:`, error)
      }
    }
    
    // 获取需求详情
    if (requirementIds.size > 0) {
      try {
        const requirementDetails = await Promise.allSettled(
          Array.from(requirementIds).map(id => getRequirementById(id))
        )
        
        for (const result of requirementDetails) {
          if (result.status === 'fulfilled' && result.value?.success && result.value?.data) {
            const requirement = result.value.data
            if (requirement && requirement.id) {
              const existingIndex = allRequirements.findIndex(req => req.id === requirement.id)
              if (existingIndex >= 0) {
                allRequirements[existingIndex] = requirement
              } else {
                allRequirements.push(requirement)
              }
            }
          }
        }
      } catch (error) {
        console.error('获取需求详情失败:', error)
      }
    }
    
    // 去重
    const uniqueRequirements = Array.from(new Map(allRequirements.map(req => [req.id, req])).values())
    relatedRequirements.value = uniqueRequirements
  } catch (error) {
    console.error('加载关联需求失败:', error)
    ElMessage.error('加载关联需求失败')
    relatedRequirements.value = []
  } finally {
    requirementsLoading.value = false
  }
}

// 添加任务
const handleAddTask = () => {
  ElMessage.info('添加任务功能待实现')
}

// 添加需求
const handleAddRequirement = () => {
  ElMessage.info('添加需求功能待实现')
}

// 查看任务
const handleViewTask = (taskId: string) => {
  router.push(`/tasks/${taskId}`)
}

// 查看需求
const handleViewRequirement = (requirementId: string) => {
  router.push(`/requirements/${requirementId}`)
}

// 移除任务
const handleRemoveTask = async (task: Task) => {
  try {
    await ElMessageBox.confirm(
      `确定要移除任务"${task.title}"的关联吗？`,
      '确认移除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    // 如果有版本ID，需要从版本缺陷关联表中移除任务关联
    if (props.versionIds && props.versionIds.length > 0) {
      // 需要通过更新版本缺陷关联记录来移除任务关联
      // 这里需要调用后端API来更新关联记录
      ElMessage.info('移除关联功能需要后端支持，请稍后重试')
      return
    }

    ElMessage.success('任务关联已移除')
    await loadRelatedTasks()
    emit('task-updated')
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('移除任务关联失败:', error)
      ElMessage.error('移除任务关联失败')
    }
  }
}

// 移除需求
const handleRemoveRequirement = async (requirement: RequirementResponse) => {
  try {
    await ElMessageBox.confirm(
      `确定要移除需求"${requirement.title}"的关联吗？`,
      '确认移除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    // 如果有版本ID，需要从版本缺陷关联表中移除需求关联
    if (props.versionIds && props.versionIds.length > 0) {
      // 需要通过更新版本缺陷关联记录来移除需求关联
      // 这里需要调用后端API来更新关联记录
      ElMessage.info('移除关联功能需要后端支持，请稍后重试')
      return
    }

    ElMessage.success('需求关联已移除')
    await loadRelatedRequirements()
    emit('requirement-updated')
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('移除需求关联失败:', error)
      ElMessage.error('移除需求关联失败')
    }
  }
}

watch(() => [props.defectId, props.versionIds], () => {
  loadRelatedTasks()
  loadRelatedRequirements()
}, { immediate: true, deep: true })

onMounted(async () => {
  await Promise.all([
    loadTaskStates(),
    loadRequirementStates(),
    loadRequirementOptions(),
    loadTaskPriorityOptions()
  ])
  loadRelatedTasks()
  loadRelatedRequirements()
})
</script>

<style scoped lang="scss">
.defect-associations-tab {
  display: flex;
  flex-direction: column;
  gap: 16px;
  padding: 16px;
}

.association-sub-tabs {
  :deep(.el-tabs__content) {
    padding: 0;
  }
}

.sub-tab-content {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.tab-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.item-count {
  font-size: 14px;
  font-weight: 600;
  color: #303133;
}

.items-list {
  min-height: 200px;
}
</style>

